package controller.member;

import databaseLayer.Member_db;
import databaseLayer.MovieSection_db;
import databaseLayer.Purchase_db;
import databaseLayer.ReservedSeat_db;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Member;
import model.MovieSection;
import model.Purchase;
import model.PurchaseId;
import util.HibernateUtil;
import util.PurchaseUtil;

public class MemberPurchaseServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String action = request.getParameter("action");
            if (action == null) {
                doDefault(request, response);
            } else if (action.equals("chooseSeats")) {
                doChooseSeats(request, response);
            } else if (action.equals("confirm")) {
                doConfirm(request, response);
            } else if (action.equals("payment")) {
                doPayment(request, response);
            } else {
                doDefault(request, response);
            }
        } catch (Exception e) {
            HttpSession session = request.getSession();
            session.setAttribute("errorMessage", e.getMessage());
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/member/search.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    private void doPayment(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        PurchaseUtil.getInstance().generalDoPayment(request, response);

        // forward to jsp
        HttpSession session = request.getSession();
        session.setAttribute("message", "Purchased successfully!");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/member/result.jsp");
        requestDispatcher.forward(request, response);
    }

    private void doDefault(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        HttpSession session = request.getSession();

        // get movie section id
        String movieSectionId = request.getParameter("id");
        MovieSection target = MovieSection_db.selectMovieSectionById(movieSectionId);
        session.setAttribute("targetMovieSection", target);

        // get user name
        String memberUsername = request.getRemoteUser();
        session.setAttribute("memberUsername", memberUsername);

        // retrieve the seat infomation
        List<String> occupiedSeats = Purchase_db.getInstance().selectOccupiedSeats(movieSectionId);
        session.setAttribute("occupiedSeats", occupiedSeats);

        List<String> reservedSeats = ReservedSeat_db.getInstance().selectReservedSeatNosByHouseId(target.getHouseId());
        session.setAttribute("reservedSeats", reservedSeats);

        // forward to JSP
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/member/chooseSeats.jsp");
        requestDispatcher.forward(request, response);
    }

    private void doChooseSeats(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        HttpSession session = request.getSession();
        String strSeats = request.getParameter("purchasedSeat");
        String[] arrSeats = strSeats.split(",");
        session.setAttribute("arrSeats", arrSeats);

        // prepare for confirm page
        session.setAttribute("numTickets", Integer.toString(arrSeats.length));

        MovieSection target = (MovieSection) session.getAttribute("targetMovieSection");
        int singleTicketPrice = target.getPrice();
        Integer totalPayment = singleTicketPrice * arrSeats.length;
        session.setAttribute("totalPayment", totalPayment);

        String memberUsername = request.getRemoteUser();
        Integer loyaltyPoint = Member_db.getInstance().getLoyaltyPoint(memberUsername);
        session.setAttribute("loyaltyPoint", loyaltyPoint);

        // forward to jsp
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/member/confirm.jsp");
        requestDispatcher.forward(request, response);
    }

    private void doConfirm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        PurchaseUtil.getInstance().generalDoConfirm(request, response);

        // forward to jsp
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/member/payment.jsp");
        requestDispatcher.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
